package com.wolfalpha.utron.activity;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormalActivity;
import com.wolfalpha.utron.adapter.RequirementAdapter;
import com.wolfalpha.utron.bean.ItemRequirement;
import com.wolfalpha.utron.service.ReuirementService;
import com.wolfalpha.utron.service.impl.RequirementServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 关于界面
 *
 * @author luodon
 */
public class RequirementActivity extends BaseNormalActivity implements View.OnClickListener {

    private RequirementAdapter adapter;         //列表适配器

    private ReuirementService reuirementService;

    private LinearLayout lyEdit;
    private RelativeLayout root;
    private EditText etContent;
    private Button btnSend;

    private XListView lvRequires;

    private final static int IPUT_SHOW = 1;
    private final static int IPUT_DISMISS = 2;
    private final static int SEND_REQ = 3;
    private final static int SHOW_LIST = 4;


    private boolean inputIsShowing = false;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            switch (msg.what) {
                case IPUT_SHOW:
                    //显示输入法
                    params.addRule(RelativeLayout.BELOW, R.id.requirement_head);
                    lyEdit.setLayoutParams(params);
                    //可以设置动画
                    lvRequires.setAlpha(0.2f);
                    break;
                case IPUT_DISMISS:
                    //退出输入法
                    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    lyEdit.setLayoutParams(params);
                    lvRequires.setAlpha(1.0f);
                    break;
                case SEND_REQ:
                    UIHelper.ToastMessage(RequirementActivity.this, "发送成功，正在穿越...");
                    etContent.setText("");
                    loadData();
                    break;
                case SHOW_LIST:
                    adapter = new RequirementAdapter(RequirementActivity.this, rqs);
                    adapter.notifyDataSetChanged();
                    lvRequires.setAdapter(adapter);
                    lvRequires.stopRefresh();
                    break;
            }
        }
    };

    private List<ItemRequirement> rqs;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_requirement);
        reuirementService = new RequirementServiceImpl();

        initView();

        initListeners();

        loadData();
    }

    /**
     * 初始化监听器
     */
    private void initListeners() {
        /**
         * 监听键盘状态，改变输入框的位置
         */
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 200) {
                    if (!inputIsShowing) {
                        handler.sendEmptyMessage(IPUT_SHOW);
                        inputIsShowing = true;
                    }
                } else {
                    //键盘隐藏
                    if (inputIsShowing) {
                        handler.sendEmptyMessage(IPUT_DISMISS);
                        inputIsShowing = false;
                    }

                }
            }
        });
        lvRequires.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                loadData();
            }

            @Override
            public void onLoadMore() {
                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        List rqsMore = reuirementService.getList(++page);
                        if (rqsMore != null) {
                            rqs.addAll(rqsMore);
                            final List finalRqsMore = rqsMore;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyDataSetChanged();
                                    lvRequires.stopLoadMore();
                                    if (finalRqsMore.size() < 10) {
                                        lvRequires.setPullLoadEnable(false);
                                    }
                                }
                            });
                        } else {
                            page--;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    lvRequires.setPullLoadEnable(false);
                                    lvRequires.stopLoadMore();
                                }
                            });
                        }
                    }
                });
            }
        });
        btnSend.setOnClickListener(this);
    }

    /**
     * 发送数据
     */
    private void sendData() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                if (reuirementService.publishOne(etContent.getText().toString().trim())) {
                    handler.sendEmptyMessage(SEND_REQ);

                } else {
                    UIHelper.ToastMessage(RequirementActivity.this, "发送失败");
                }
                InputMethodManager m = (InputMethodManager)
                        RequirementActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (m.isActive()) {
                    m.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                }
            }
        });
    }

    private int page = 1;

    /**
     * 加载数据
     */
    private void loadData() {
        page = 1;
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                rqs = new ArrayList<ItemRequirement>();
                rqs = reuirementService.getList(page);
                if (rqs != null) {
                    handler.sendEmptyMessage(SHOW_LIST);
                    if (rqs.size() < 10) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                lvRequires.setPullLoadEnable(false);
                            }
                        });
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            lvRequires.setPullLoadEnable(false);
                            lvRequires.stopRefresh();
                        }
                    });
                }
            }
        });
    }

    /**
     * 初始化布局
     */
    private void initView() {
        setTvTitle("我的需求");

        etContent = (EditText) findViewById(R.id.et_require_content);
        root = (RelativeLayout) findViewById(R.id.requirement_root);
        lyEdit = (LinearLayout) findViewById(R.id.ly_edit);
        btnSend = (Button) findViewById(R.id.btn_require_send);
        lvRequires = (XListView) findViewById(R.id.lv_require);
        lvRequires.setPullLoadEnable(true);
    }


    @Override
    public void onClick(View v) {
        if (!TextUtils.isEmpty(etContent.getText().toString().trim())) {
            sendData();
        } else {
            UIHelper.ToastMessage(RequirementActivity.this, "请先输入内容");
        }
    }
}
